<template>
  <van-field
    v-model="item.value"
    :disabled="options.disabled"
    :name="item.itemTitle"
    :readonly="type === 'view' || options.disabled"
    :required="item.isRequired === 'Y'"
    :rules="[{ validator: validatorMessage }]"
    :type="options.validation"
    label-width="33rem"
    placeholder="请填写"
    @change="onChange"
  >
    <template #label>
      <span>{{ titleText(options, item) }}</span>
      <p v-if="options.showDesc" class="desc f12 mb10 ml30">
        {{ options.description }}
      </p>
    </template>
  </van-field>
</template>

<script setup>
import {
  chinese,
  decimal,
  email,
  idCard,
  letter,
  letterAndNumber,
  mobilePhone,
  noChinese,
  number,
  url,
} from "@/utils/validator.js";

import { titleText } from "@/utils/common.js";


//defineOptions({ name: "H5MemberName" });

const { item, type } = defineProps(["item", "type"]);
const emits = defineEmits(["change"]);

const { options } = JSON.parse(item.vformJson);
// 传递值改变后
const onChange = () => emits("change", item);

// 校验
const validatorMessage = (val) => {
  if (item.value) {
    let regex = {
      number,
      decimal,
      letter,
      letterAndNumber,
      mobilePhone,
      email,
      url,
      noChinese,
      chinese,
      idCard,
    };
    let hasReg = regex[options.validation];
    if (hasReg && !hasReg.test(item.value))
      return `请输入正确的${item.itemTitle}`;
  }
  if (item.isRequired === "Y") {
    let length = item.value ? item.value.length : 0;
    if (length === 0) {
      return "请填写" + item.itemTitle;
    } else {
      if (options.minLength && length < options.minLength) {
        return `字符长度不能少于${options.minLength}`;
      }
      if (options.maxLength && length > options.maxLength) {
        return `字符长度不能大于${options.maxLength}`;
      }
    }
  }
};
</script>